﻿using System.Collections.Generic;
using System;
using System.Runtime.CompilerServices;

namespace Db7.Collections
{
    public class StringAttributes
    {
        private Dictionary<string, string> _dict = new Dictionary<string, string>();

        public Dictionary<string, GetSetStringAttribute> ReservedProperties;

        public Dictionary<string, GetSetStringAttribute> ReservedPropertiesNN
        {
            get
            {
                if (ReservedProperties == null) ReservedProperties = new Dictionary<string, GetSetStringAttribute>();
                return ReservedProperties;
            }
        }


        public void SetKey(string key, string value)
        {
            if (ReservedProperties != null && ReservedProperties.ContainsKey(key))
            {
                ReservedProperties[key].Set(value);
            }
            else
            {
                _dict[key] = value;
            }
            //NotifySubscribers(key, value);

        }

        public string GetValue(string key)
        {
            if (ReservedProperties != null)
            {
                if (ReservedProperties.ContainsKey(key))
                {
                    GetSetStringAttribute gsp = ReservedProperties[key];
                    return gsp.Get();
                }
            }
            if (_dict.ContainsKey(key))
            {
                return _dict[key];
            }
            return null;
        }

        //[IntrinsicProperty]
        //public string this[string key]
        //{
        //    get { return GetValue(key); }
        //    set { SetKey(key, value); }
        //}

        public override string ToString()
        {
            StringBuilder sw = new StringBuilder();
            bool first = true;
            string space = " ";
            foreach (KeyValuePair<string, string> kvp in this._dict)
            {
                if (!first) sw.Append(space);
                first = false;
                sw.Append(kvp.Key + "='" + kvp.Value + "'");
            }
            if (this.ReservedProperties != null)
            {
                foreach (KeyValuePair<string, GetSetStringAttribute> kvp in this.ReservedProperties)
                {
                    if (!first) sw.Append(space);
                    first = false;
                    sw.Append(kvp.Key + "='" + kvp.Value.Get() + "'");
                }
            }
            return sw.ToString();
        
        }
    }

    public class GetSetStringAttribute
    {
        public Action<string> Set;
        public Func<string> Get;
    }
}
